# 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app

# 安装构建依赖
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    cairo-dev \
    jpeg-dev \
    pango-dev \
    giflib-dev \
    pixman-dev

# 复制package文件
COPY package*.json ./
COPY prisma ./prisma/

# 安装依赖（使用npm install代替npm ci，因为没有package-lock.json）
RUN npm install --production && \
    npm cache clean --force

# 生成Prisma Client
RUN npx prisma generate

# 生产阶段
FROM node:18-alpine

WORKDIR /app

# 安装SQLite和构建工具（用于编译native模块）
RUN apk add --no-cache \
    sqlite \
    python3 \
    make \
    g++ \
    cairo-dev \
    jpeg-dev \
    pango-dev \
    giflib-dev \
    pixman-dev

# 创建非root用户
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001

# 从构建阶段复制依赖
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/prisma ./prisma

# 复制源代码
COPY --chown=nodejs:nodejs . .

# 创建数据目录
RUN mkdir -p /data /app/backups && \
    chown -R nodejs:nodejs /data /app/backups

# 切换到非root用户
USER nodejs

# 暴露端口
EXPOSE 5211

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD node -e "require('http').get('http://localhost:5211/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# 启动应用
CMD ["node", "src/index.js"]


